<template>
  <div id="lightController" class="wrapper" style="overflow-x: auto">
    <!--搜索-->
    <div class="mb-3 d-flex align-items-center"  style="min-width: 1184px">
      <div class="d-flex align-items-center">
        <!--<el-input placeholder="请输入内容"  class="input-with-select w400"  size="small" v-model="searchTxt">-->
          <!--<el-select class="w140" v-model="searchType" slot="prepend" placeholder="请选择" @change="querLightInfo">-->
            <!--<el-option label="控制箱" :value="1"></el-option>-->
            <!--<el-option label="NB单灯分组" :value="2"></el-option>-->
            <!--<el-option label="NB单灯" :value="3"></el-option>-->
          <!--</el-select>-->
          <!--<el-button  slot="append"  class="ur-btn ur-btn-primary" @click="querLightInfo"><i class="iconfont icon-sousuo"></i>查询</el-button>-->
        <!--</el-input>-->
        责任区：
        <el-select class="w100 mr-1" v-model="pole.regionId" slot="prepend" placeholder="请选择" size="small" @change="querLightInfo">
          <el-option label="全部" :value="-1"></el-option>
          <el-option v-for="(item,index) in regions" :key="index" :label="item.Name" :value="item.Id"></el-option>
        </el-select>
        分组：
        <el-select class="w140 mr-2" v-model="pole.groupId" slot="prepend" placeholder="请选择" size="small" @change="querLightInfo">
          <el-option label="全部" :value="-1"></el-option>
          <el-option v-for="(item,index) in groups" :key="index" :label="item.GroupName" :value="item.Id"></el-option>
        </el-select>
        <el-input placeholder="请输入内容"  class="input-with-select w180"  size="small" v-model="pole.value">
          <el-button v-if="limits.indexOf('2_06_03_01')!=-1" slot="append"  class="ur-btn ur-btn-primary" @click="querLightInfo">查询</el-button>
        </el-input>

        <el-button v-if="limits.indexOf('2_06_03_02')!=-1" class="ur-btn ur-btn-primary w120 ml-2" @click="onOffCtrl"><i class="iconfont icon-dankong"></i>开关灯调光</el-button>
        <el-button v-if="limits.indexOf('2_06_03_03')!=-1" class="ur-btn ur-btn-primary w75" @click="clickFun(1)"><i class="iconfont icon-xiaoshi"></i>校时</el-button>
        <!--<el-button class="ur-btn ur-btn-primary w75" @click="clickFun(2)"><i class="iconfont icon-refresh-1-copy"></i>复位</el-button>-->
        <el-button v-if="limits.indexOf('2_06_03_05')!=-1" class="ur-btn ur-btn-primary w75" @click="clickFun(3)"><i class="iconfont icon-kaiguan"></i>重启</el-button>
      </div>
      <ul class="result_group ml-auto">
        <li>下发总计：{{callNum.total}}</li>
        <li><i class="circle success"></i>成功：{{callNum.success}}</li>
        <li><i class="circle error"></i>失败：{{callNum.error}}</li>
      </ul>
    </div>
    <!--表格-->
    <el-table ref="ligthTable" :data="getGidData" style="min-width: 1184px" :height="clientHeight-202" highlight-current-row @selection-change="selsChange">
      <el-table-column type="selection" width="50" align="center"></el-table-column>
      <el-table-column align="center" type="index" :index="indexMethod" label="序号" width="50"></el-table-column>
      <el-table-column v-for="(v,index) in tables.columns" :prop="v.field" :label="v.title" :width="v.width" align="center" :key="index">
        <template slot-scope="scope">
          <span v-if="v.field=='result'">
            <template v-if="scope.row[v.field]===1"><i class="circle success" ></i>成功</template>
            <template v-else-if="scope.row[v.field]===0"><i class="circle error" ></i>失败</template>
            <template v-else>{{scope.row.result}}</template>
          </span>
          <span v-else>{{scope.row[v.field]}}</span>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <div class="my-3 d-flex justify-content-between align-items-center">
      <div class="" >
        <label>下发结果：</label>
        <div class="progress  w200 d-inline-block" style="height: 16px;vertical-align: middle">
          <div ref="progressBar" class="progress-bar progress-bar-striped" role="progressbar" style="width:0" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"></div>
        </div>
      </div>
      <el-pagination class=" " @size-change="handleSizeChange" @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper"
                     :page-sizes="[100,200,500,1000]" :current-page="currentPage" :page-size="pageSize" :total="total"></el-pagination>
    </div>

    <!--开关灯调光弹框-->
    <el-dialog v-el-drag-dialog title="单灯控制" :visible.sync="showLightOnOff" width="516px" top="12%" :close-on-click-modal="false" @close="showLightOnOff=false">
      <template v-if="showLightOnOff">
        <light-ctrl :poles="sels" :lightType="'nb'" @updateResult="updateResult" @updateBar="updateBar"></light-ctrl>
      </template>
    </el-dialog>

    <el-dialog v-el-drag-dialog :title="dialogTitle" :visible.sync="dialogCtrl" width="390px" top="20%">
      <div class="p-4" v-if="dialogCtrl">
        <div class="form-inline">
          <label>操作密码：</label>
          <el-tooltip class="item" :content="errors.first('pwd')" :value="errors.has('pwd')" :manual="true">
            <el-input type="password" size="small" class="w180" :class="{'is-error':errors.has('pwd')}" v-model="operatePwd" v-validate="'required'" name="pwd"></el-input>
          </el-tooltip>
          <el-button class="ur-btn w75 ml-3" :class="{'ur-btn-primary':!btnState}" type="info" @click="callFun" :disabled="btnState"><i class="iconfont icon-queding"></i>下发</el-button>
        </div>
        <!--<p class="text-danger mt-4">注：对所有设备进行控制</p>-->
      </div>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
  import {mapState} from 'vuex'
  import api from 'api/api'
  import fetch from 'api/fetch'
  import elDragDialog from 'directive/el-dragDialog'
  import lightCtrl from './light-controller'

  export default {
    directives:{elDragDialog},
    components: {
      lightCtrl
    },
    props: {},
    data() {
      return {
        total: 0,
        currentPage: 1,
        pageSize:100,
        searchType:1,
        searchTxt:'',
        tables: {
          sel: null,//选中行
          columns:  [
            {field: "PoleNo", title: "灯杆编号", width: '120'},
            {field: "BoxNo", title: "所属控制箱", width: null},
            {field: "PoleDevAddr", title: "设备地址", width: null},
            {field: "AreaName", title: "责任区", width: null},
            {field: "opereaTime", title: "执行时间", width: null},
            {field: "result", title: "下发结果", width: null},
            {field: "resultInfo", title: "失败原因", width: null},
          ],
          data: []
        },
        sels:[],
        PoleIds:[],
        showLightOnOff:false,
        callNum:{total:0,success:0,error:0},
        regions:[],
        groups:[],
        pole:{regionId:-1,groupId:-1,value:''},
        btnIndex:0,
        dialogTitle:'',
        dialogCtrl:false,
        operatePwd:'',
        btnState:false
      }
    },
    watch: {},
    computed: {
      getGidData(){
        if(this.tables.data.length){
          return this.tables.data.slice((this.currentPage-1)*this.pageSize,this.currentPage*this.pageSize)
        }
      },
      ...mapState({
        clientHeight:state=>state.comm.clientHeight,
        clientWidth:state=>state.comm.clientWidth,
        limits:state=>state.user.userInfo.limits
      })
    },
    methods: {
      indexMethod(index) {
        return index + 1
      },
      selsChange(sels) {
        this.PoleIds=[]
        this.sels = sels
        sels.map(pole=>{
          this.PoleIds.push(pole.PoleId)
        })
        this.sels.splice(0,0)
      },
      clickFun(type){
        //type 1:校时 2：复位 3：重启
        this.btnIndex=type
        this.clearResult(this.PoleIds,'start')
        this.dialogCtrl=true
        switch (type){
          case 1:
            return this.dialogTitle='校时'
          case 2:
            return this.dialogTitle='复位'
          case 3:
            return this.dialogTitle='重启'
        }
      },
       async callFun() {
        let url = '', data = ''
        let callIndex =  this.btnIndex
        let rebootType=1
        let rows=this.sels
        if (this.sels.length == 0) return this.$message.warning({showClose:true,message:'未选择单灯'})
        this.$refs.progressBar.textContent = ''
        this.$refs.progressBar.style.width = 0
         let res=await this.$validator.validateAll()
         if(!res) return
         this.$store.commit('user/SET_USER_PWD', this.operatePwd)
         let pIndex = 1
         rows.map((pole, index, arr) => {
           if (callIndex == 1 ) {//1校时
             url = '/Communication/NB/AFN05F31'
             data = {tnDevAddr: pole.PoleDevAddr}
           } else if (callIndex == 2||callIndex == 3) {//2复位 3重启
             url = '/Communication/NB/AFN05F10'
             if (callIndex == 3) rebootType = 2
             data = {tnDevAddr: pole.PoleDevAddr, rebootType: rebootType}
           }
           //金山验收需要：临时修改
         /*  let r=api.fetchSimple(url, data)
           pole.opereaTime=api.formatDate(new Date(),'yyyy-MM-dd HH:mm:ss')
           this.callNum.success++
           pole.result = 1
           pole.resultInfo = ''
           let pcen = Math.round(pIndex / arr.length * 100) > 100 ? 100 : Math.round(pIndex / arr.length * 100)
           this.updateBar(pcen)
           pIndex++
           if (pcen == 100) {
             this.btnState=false
             this.dialogCtrl = false
             this.callNum.total = this.callNum.error + this.callNum.success
             this.clearResult(this.PoleIds,'end')
           }*/
           api.fetchSimple(url, data)
             .then(r => {
               this.btnState=true
               pole.opereaTime=api.formatDate(new Date(),'yyyy-MM-dd HH:mm:ss')
               if (r.err) {
                 this.callNum.error++
                 pole.result = 0
                 pole.resultInfo = r.err
               } else {
                 this.callNum.success++
                 pole.result = 1
                 pole.resultInfo = ''
               }
               let pcen = Math.round(pIndex / arr.length * 100) > 100 ? 100 : Math.round(pIndex / arr.length * 100)
               this.updateBar(pcen)
               pIndex++
               if (pcen == 100) {
                 this.btnState=false
                 this.dialogCtrl = false
                 this.callNum.total = this.callNum.error + this.callNum.success
                 this.clearResult(this.PoleIds,'end')
               }
             })
        })
      },
      onOffCtrl(){
        if(!this.sels.length) return this.$message.warning({showClose:true,message:'请勾选NB单灯'})
        this.showLightOnOff=true
        this.clearResult(this.PoleIds,'start')
      },
      updateResult(v) {
        this.callNum = v.callNum
        this.clearResult(v.PoleIds,'end')
      },
      clearResult(PoleIds,type){
        this.operatePwd=''
        this.$refs.ligthTable.clearSelection()
        this.tables.data.forEach(pole => {
          let index=PoleIds.indexOf(pole.PoleId)
          if (index != -1) this.$refs.ligthTable.toggleRowSelection(pole)
          if(type=='start'){//操作前清空结果
            this.callNum = {total: 0, success: 0, error: 0}
            this.$refs.progressBar.style.width =0
            this.$refs.progressBar.textContent =''
            pole.result=''
            pole.resultInfo = ''
            pole.opereaTime = ''
          }
        })
      },
      updateBar(pcen){//更新进度条宽度
        this.$refs.progressBar.style.width = pcen + '%'
        this.$refs.progressBar.textContent = pcen + '%'
      },
      querLightInfo(){
        this.currentPage=1
        // this.columns=this.searchType==2?this.tables.columns[1]:this.tables.columns[0]
        api.fetchSimple('/Manual/QueryNBLightCtlInfo',this.pole)
          .then(r => {
            if(r.data){
              this.tables.data = r.data
              this.total=r.data.length
            }else{
              this.tables.data=[]
              this.total=0
              // this.$message.success('未查询到数据')
            }
          })
      },
      handleSizeChange(val) {
        this.pageSize=val
      },
      handleCurrentChange(val) {
        this.currentPage=val
      },
      queryRegion(){
        fetch.queryArea()
          .then(r=>{
            this.regions=r.data
          })
      },
      queryGroup(){
        this.groups=[]
        fetch.queryGroup()
          .then(r=>{
            r.data.map(r=>{
              if(r.Type==3){
                this.groups.push(r)
              }
            })
          })
      }
    },
    created() {
      this.queryRegion()
      this.queryGroup()
      this.querLightInfo()
    },
    mounted() {
    }
  }
</script>
<style scoped lang="stylus" rel="stylesheet/stylus">
</style>
